from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.service.dict_service import DictDataService
from module_rag.dao.rag_dao import RagDao
from module_rag.entity.vo.rag_vo import DeleteRagModel, RagModel, RagPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from utils.page_util import PageResponseModel


class RagService:
    """
    知识库信息模块服务层
    """

    @classmethod
    async def get_rag_list_services(
        cls, query_db: AsyncSession, query_object: RagPageQueryModel, is_page: bool = False
    ):
        """
        获取知识库信息列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 知识库信息列表信息对象
        """
        query_result = await RagDao.get_rag_list(query_db, query_object, is_page)
        if is_page:
            rag_list_result = PageResponseModel(
                **{
                    **query_result.model_dump(by_alias=True),
                    'rows': [{**row[0], 'user': row[1]} for row in query_result.rows],
                }
            )
        else:
            rag_list_result = []
            if query_result:
                rag_list_result = [{**row[0], 'user': row[1]} for row in query_result]

        return rag_list_result


    @classmethod
    async def add_rag_services(cls, query_db: AsyncSession, page_object: RagModel):
        """
        新增知识库信息信息service

        :param query_db: orm对象
        :param page_object: 新增知识库信息对象
        :return: 新增知识库信息校验结果
        """
        try:
            await RagDao.add_rag_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_rag_services(cls, query_db: AsyncSession, page_object: RagModel):
        """
        编辑知识库信息信息service

        :param query_db: orm对象
        :param page_object: 编辑知识库信息对象
        :return: 编辑知识库信息校验结果
        """
        edit_rag = page_object.model_dump(exclude_unset=True, exclude={'user_id', 'create_time', 'create_by', })
        rag_info = await cls.rag_detail_services(query_db, page_object.id)
        if rag_info.id:
            try:
                await RagDao.edit_rag_dao(query_db, edit_rag)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='知识库信息不存在')

    @classmethod
    async def delete_rag_services(cls, query_db: AsyncSession, page_object: DeleteRagModel):
        """
        删除知识库信息信息service

        :param query_db: orm对象
        :param page_object: 删除知识库信息对象
        :return: 删除知识库信息校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await RagDao.delete_rag_dao(query_db, RagModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入知识库id为空')

    @classmethod
    async def rag_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取知识库信息详细信息service

        :param query_db: orm对象
        :param id: 知识库id
        :return: 知识库id对应的信息
        """
        rag = await RagDao.get_rag_detail_by_id(query_db, id=id)
        if rag:
            result = RagModel(**CamelCaseUtil.transform_result(rag))
        else:
            result = RagModel(**dict())

        return result

    @staticmethod
    async def export_rag_list_services(request: Request, rag_list: List):
        """
        导出知识库信息信息service

        :param rag_list: 知识库信息信息列表
        :return: 知识库信息信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': '知识库id',
            'ragTitle': '知识库名称',
            'userId': '创建用户id',
            'sumary': '知识库摘要',
            'status': '知识库状态',
            'createTime': '创建时间',
            'createBy': '创建人',
            'updateTime': '更新时间',
            'updateBy': '更新人',
        }
        bjj_rag_status_list = await DictDataService.query_dict_data_list_from_cache_services(
            request.app.state.redis, dict_type='bjj_rag_status'
        )
        bjj_rag_status_option = [dict(label=item.get('dictLabel'), value=item.get('dictValue')) for item in bjj_rag_status_list]
        bjj_rag_status_option_dict = {item.get('value'): item for item in bjj_rag_status_option}
        for item in rag_list:
            if str(item.get('status')) in bjj_rag_status_option_dict.keys():
                item['status'] = bjj_rag_status_option_dict.get(str(item.get('status'))).get('label')
        binary_data = ExcelUtil.export_list2excel(rag_list, mapping_dict)

        return binary_data
